import axios from 'axios';
import Cookies from 'js-cookie';

// API基础配置
const API_BASE_URL = '/api';

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  }
});

// 请求拦截器
apiClient.interceptors.request.use(
  (config) => {
    // 可以在这里添加通用的请求头
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
apiClient.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    console.error('API请求错误:', error);
    return Promise.reject(error);
  }
);

// 模型相关API
export const modelApi = {
  // 获取模型列表（移除分页）
  getModelList: async (params = {}) => {
    const { search = '', occ = '' } = params;
    return apiClient.get('/model/list', {
      params: { search, occ }
    });
  },

  // 根据ID获取模型详情
  getModelById: async (id) => {
    return apiClient.get(`/model/${id}`);
  },

  // 获取模型统计信息
  getModelStats: async () => {
    return apiClient.get('/model/stats');
  },

  // 获取职业列表
  getOccupationList: async () => {
    return apiClient.get('/model/occupations');
  },

  // 根据职业查询模型列表
  getModelsByOccupation: async (occupation) => {
    return apiClient.get('/model/list/occupation', {
      params: { occupation }
    });
  },

  // 根据分类查询模型列表
  getModelsByCategory: async (category) => {
    return apiClient.get('/model/list/category', {
      params: { category }
    });
  },

  // 搜索模型
  searchModels: async (keyword) => {
    return apiClient.get('/model/search', {
      params: { keyword }
    });
  },

  // 获取热门模型
  getTopModels: async (limit = 10) => {
    return apiClient.get('/model/top', {
      params: { limit }
    });
  },

  // 生成下载token
  generateDownloadToken: async (modelId, username) => {
    return apiClient.post(`/model/token/${modelId}`, null, {
      params: { username: username || 'anonymous' }
    });
  },

  // 下载模型（需要token验证）
  downloadModel: async (modelId, token, username) => {
    return apiClient.post(`/model/download/${modelId}`, null, {
      params: { username: username || 'anonymous' },
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
  },

  // 访问模型详情（记录访问日志）
  viewModelDetail: async (modelId, username) => {
    return apiClient.get(`/model/detail/${modelId}`, {
      params: { username: username || 'anonymous' }
    });
  }
};

// 统计相关API
export const statisticsApi = {
  // 获取系统统计信息
  getSystemStatistics: async () => {
    return apiClient.get('/statistics/system');
  },

  // 获取职业统计
  getOccupationStats: async () => {
    return apiClient.get('/statistics/occupation');
  },

  // 获取分类统计
  getCategoryStats: async () => {
    return apiClient.get('/statistics/category');
  },

  // 获取热门模型统计
  getTopModelsStats: async () => {
    return apiClient.get('/statistics/top-models');
  }
};

// 用户相关API
export const userApi = {
  // 用户登录
  login: async (username, password) => {
    const formData = new URLSearchParams();
    formData.append('username', username);
    formData.append('password', password);
    return apiClient.post('/login', formData, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    });
  },

  // 用户注册
  register: async (username, password, code, qq) => {
    const formData = new URLSearchParams();
    formData.append('username', username);
    formData.append('password', password);
    formData.append('code', code);
    formData.append('qq', qq);
    return apiClient.post('/register', formData, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    });
  },

  // 用户登出
  logout: async (username) => {
    const formData = new URLSearchParams();
    formData.append('username', username);
    return apiClient.post('/logout', formData, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    });
  }
};

export default {
  modelApi,
  statisticsApi,
  userApi
};
